<?php


namespace app\cms\community\lib;

use iflow\Response;
use think\Model;

/**
 * 模型统计数据
 * Class statisticsModel
 * @package app\cms\community\lib
 */
class statisticsModel
{

    protected Model $model;
    protected string $startTime;
    protected string $endTime;
    protected string $type;
    protected array  $where = [];

    public function __construct(string $model)
    {
        if (!class_exists($model)) throw new \Exception('统计数据模型不存在');
        $this->model = new $model;
    }

    /**
     * 设置开始时间
     * @param string $startTime
     * @return static
     */
    public function setStartTime(string $startTime): static
    {
        $this->startTime = $startTime;
        return $this;
    }

    /**
     * 设置结束时间
     * @param string $endTime
     * @return statisticsModel
     */
    public function setEndTime(string $endTime): static
    {
        $this->endTime = $endTime;
        return $this;
    }

    /**
     * 设置时间类型
     * @param string $type | year/month/week/day
     * @return static
     */
    public function setType(string $type): static
    {
        $this->type = $type;
        return $this;
    }

    /**
     * 设置条件
     * @param array $where
     * @return static
     */
    public function setWhere(array $where): static
    {
        $this->where = $where;
        return $this;
    }

    /**
     * 执行查询 获取数据
     * @return mixed
     */
    private function query() {
         return $this->model
            -> where($this->where)
            // 周
            -> field("any_value(FROM_UNIXTIME(create_time, '%Y-%u')) as week")
            -> field("any_value(FROM_UNIXTIME(date_sub(FROM_UNIXTIME(create_time), INTERVAL dayOfWeek(FROM_UNIXTIME(create_time)) - 2 DAY ), '%Y-%m-%d')) as create_times")
            // 月
            -> field("any_value(FROM_UNIXTIME(create_time, '%Y-%m')) as month")
            // 日
            -> field("any_value(FROM_UNIXTIME(create_time, '%Y-%m-%d')) as day")
            // 年
            -> field("any_value(DATE_FORMAT(create_time, '%Y')) as year")
            -> field('any_value(count(*)) as total')
            -> whereBetweenTime('create', $this->startTime, $this->endTime)
            -> group($this->type)
            -> select() -> toArray();
    }

    /**
     * 统计模型新增
     */
    public function statisticsInc(): Response
    {
        $data = $this->query();
        $count = count($data);
        if ($count <= 0) return message() -> nodata('暂无数据');

        if ($count <= 1) return message() -> success('查询成功', [
            'data' => $data
        ]);

        return message() -> success('查询成功', [
            'data' => $data,
            'inc' => $data[$count - 1]['count'] - $data[$count - 2]['count'],
            'percentage' => $data[$count - 1] / $data[$count - 2] * 100
        ]);
    }

    /**
     * 统计模型递减
     */
    public function statisticsDec()
    {}
}